import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Tabs, Cell, Button, Image, Toast, Loading } from "@nutui/nutui-react";
import { ArrowLeft, Cart } from "@nutui/icons-react";
import { api } from "@/api/api";
import { useSelector } from "react-redux";
import { truncateProductDescription } from "@/utils/truncateText";
import "./index.less";

const ProductsView = () => {
  const navigate = useNavigate();
  const shopId = useSelector((state) => state.user.shopId);
  const userInfo = useSelector((state) => state.user.userInfo);
  const [activeTab, setActiveTab] = useState(0);
  const [products, setProducts] = useState({
    all: [],
    group1: [],
    group2: [],
    group3: []
  });
  const [loading, setLoading] = useState(false);
  const [addingToCart, setAddingToCart] = useState({});

  const categories = [
    { id: 0, name: "全部", key: "all" },
    { id: 1, name: "药食同源", key: "group1" },
    { id: 2, name: "养生茶饮", key: "group2" },
    { id: 3, name: "科技理疗", key: "group3" }
  ];

  const handleBack = () => {
    navigate(-1);
  };

  const fetchProducts = async (groupId = 0) => {
    if (!shopId) {
      Toast.show("门店信息缺失");
      return;
    }

    setLoading(true);
    try {
      const response = await api.getAllProducts({
        shopId: shopId,
        groupId: groupId
      });

      if (response.code === 200) {
        return response.data || [];
      } else {
        Toast.show(response.message || "获取商品失败");
        return [];
      }
    } catch (error) {
      Toast.show("获取商品失败，请重试");
      return [];
    } finally {
      setLoading(false);
    }
  };

  const loadAllProducts = async () => {
    setLoading(true);
    try {
      const [allProducts, group1Products, group2Products, group3Products] = await Promise.all([
        fetchProducts(0),
        fetchProducts(1),
        fetchProducts(2),
        fetchProducts(3)
      ]);

      setProducts({
        all: allProducts,
        group1: group1Products,
        group2: group2Products,
        group3: group3Products
      });
    } catch (error) {
    } finally {
      setLoading(false);
    }
  };

  const handleTabChange = (index) => {
    setActiveTab(index);
  };

  const handleAddToCart = async (product) => {
    try {
      setAddingToCart(prev => ({ ...prev, [product.productId]: true }));
      const response = await api.addToCart({
        productId: product.productId,
        quantity: 1,
        shopId: shopId,
        userId: userInfo?.id || userInfo?.userId || userInfo?.user_id || userInfo?.wxUserId
      });

      if (response.code === 200) {
        Toast.show({
          content: "已添加到购物车",
          type: "success"
        });
      } else {
        Toast.show({
          content: response.message || "添加失败",
          type: "fail"
        });
      }
    } catch (error) {
      console.error("添加到购物车失败:", error);
      Toast.show({
        content: "添加失败，请重试",
        type: "fail"
      });
    }
    setAddingToCart(prev => ({ ...prev, [product.productId]: false }));
  };

  useEffect(() => {
    loadAllProducts();
  }, [shopId]);

  const renderProductList = (productList) => {
    if (loading) {
      return (
        <div className="loading-container">
          <Loading type="spinner" size="24" />
          <div className="loading-text">加载中...</div>
        </div>
      );
    }

    if (!productList || productList.length === 0) {
      return (
        <div className="empty-container">
          <div className="empty-text">暂无商品</div>
        </div>
      );
    }

    return (
      <div className="product-list">
        {productList.map((product) => (
          <div key={product.productId} className="product-item">
            <div className="product-image">
              <Image
                src={product.productImgUrl}
                alt={product.productName}
                width="100%"
                height="120px"
                fit="cover"
              />
              <div className="product-tag">
                {product.productGroupName}
              </div>
            </div>
            <div className="product-info">
              <div className="product-name">{product.productName}</div>
              <div className="product-desc">{truncateProductDescription(product.productDescription)}</div>
              <div className="product-price">
                <span className="price">¥{(product.productPriceYuan || product.productPrice / 100).toFixed(2)}</span>
                {product.originalPrice && product.originalPrice > product.productPrice && (
                  <span className="original-price">¥{(product.originalPrice / 100).toFixed(2)}</span>
                )}
              </div>
              <Button
                type="primary"
                size="small"
                className="add-cart-btn"
                loading={addingToCart[product.productId]}
                icon={<Cart />}
                onClick={() => handleAddToCart(product)}
              >
                加入购物车
              </Button>
            </div>
          </div>
        ))}
      </div>
    );
  };

  return (
    <div className="products-page">
      {/* 标签页 */}
      <div className="products-content">
        <Tabs
          value={activeTab}
          onChange={handleTabChange}
          className="products-tabs"
          activeType="smile"
        >
          {categories.map((category, index) => (
            <Tabs.TabPane key={category.key} title={category.name}>
              {renderProductList(products[category.key])}
            </Tabs.TabPane>
          ))}
        </Tabs>
      </div>
    </div>
  );
};

export default ProductsView;
